package com.dreammakerteam.frameworkdemo.base.config.shiro;

import com.dreammakerteam.frameworkdemo.base.domain.DUserDo;
import com.dreammakerteam.frameworkdemo.base.service.DUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.Realm;
import org.springframework.stereotype.Component;

@Component("dMTRealm")
public class DMTRealm implements Realm {

    private DUserService DUserService;
    public DMTRealm(DUserService DUserService) {
        this.DUserService = DUserService;
    }

    public String getName() {
        return "MyRealm1";
    }

    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String)token.getPrincipal();  //得到用户名
        String password = new String((char[])token.getCredentials()); //得到密码

        DUserDo user = DUserService.getByUsernameAndPassword(username, password);

        if(user == null) {
            throw new UnknownAccountException(); //如果用户不存在错误
        }

        //如果身份认证验证成功，返回一个AuthenticationInfo实现；
        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
